package com.resource.util.bean;

import cn.hutool.core.bean.BeanDesc;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import org.springframework.beans.BeanUtils;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public interface IBean  extends Serializable {

	@SuppressWarnings("unchecked")
	default <T> T copyAttr(Object source) {
		if(source!=null) {
			BeanUtils.copyProperties(source, this);
		}
		 return (T) this;
	}
	
	default <T> T copyTo(T  target) {
		if(target!=null) {
			BeanUtils.copyProperties(this, target);
		}
		return target;
	}

	default void setAttr(String attr,Object value){
		BeanDesc beanDesc = BeanUtil.getBeanDesc(this.getClass());
		Field field = beanDesc.getField(attr);

		String name = field.getName();
		Class<?> type = field.getType();
		if (LocalDate.class == type){
			String str = Convert.toStr(value, "");
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
			LocalDate parse = LocalDate.parse(str, formatter);
			value = parse;
		}else if (LocalDateTime.class == type){
			String str = Convert.toStr(value, "");
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
			LocalDateTime parse = LocalDateTime.parse(str, formatter);
			value = parse;
		}
		System.err.println(value);
		if (field!=null){
			BeanUtil.setFieldValue(this,attr,value);
		}else {
			throw new RuntimeException("解析异常！");
		}
	}

	default Object getAttr(String attr){
		System.err.println(attr);
		BeanDesc beanDesc = BeanUtil.getBeanDesc(this.getClass());
		Field field = beanDesc.getField(attr);
		String name = field.getName();
		Object value = BeanUtil.getFieldValue(this, name);
		System.err.println(value);
		return value;
	}



}